# coding:utf-8
import hashlib
import requests
import time
import re
from IMEI import get_imei
from rpc_58 import decrypt_phone, get_script
requests.packages.urllib3.disable_warnings()

class _58:
    def __init__(self):
        self.imei = '353490069871107'
        self.uuid = 'de448adb-d863-4b0c-8c40-75466bbc12c6'
        self.mac = 'F8:A9:D0:54:C3:0A'
        self.location = '172,177,8777'
        self.phone_type = 'Nexus 5'
        self.path = './location.txt'
        self.scripts = get_script()
        self.headers = {
            'xxzl_smartid': '',
            'uuid': self.uuid,
            'maptype': '2',
            # 'dirname': 'nj',
            'version': '8.16.5',
            'osarch': 'armeabi-v7a',
            'nettype': 'wifi',
            '58ua': '58app',
            'PPU': '',
            'apkbus': '',
            'm': self.mac,
            'owner': 'baidu',
            'rnsoerror': '0',
            'nop': '',
            'currentcid': '172',
            'platform': 'android',
            '58mac': self.mac,
            # 'location': '172,177,11840',
            'jumpextra': '{"spm":"","utm_source":""}',
            'channelid': '59',
            'r': '1776_1080',
            'product': '58app',
            'official': 'true',
            'lon': '118.793313',
            'osv': '6.0.1',
            'marketchannelid': '59',
            # 'id58': '102767863189697',
            'rimei': self.imei,
            'totalsize': '12.6',
            'Accept-Encoding': 'gzip,deflate',
            'bundle': 'com.wuba',
            'imei': self.imei,
            # 'bangbangid': '1080866210667397614',
            'productorid': '1',
            'apn': 'WIFI',
            # 'androidid': 'bac6e82bef66c1b4',
            'cid': '172',
            # 'deviceid': 'bac6e82bef66c1b4',
            # 'ltext': '%E6%B4%AA%E6%AD%A6%E8%B7%AF',
            'os': 'android',
            'locationstate': '1',
            'brand': 'google',
            'ua': self.phone_type,
            'uid': '',
            # 'lat': '32.036061',
            'jumpinfo': '',
            # 'Host': 'app.58.com',
            'Connection': 'Keep-Alive',
            'User-Agent': 'okhttp/3.4.2',
        }

    def location_info(self, area):
        url = 'https://app.58.com/api/baseCore/unity/update?'
        params = {
            'openurlwlver': '0',
            'subwayver': '1.0.0.0',
            'wcVersion': '',
            'cityid': '174',
            'dirname': area,
            'channelid': '59',
            'rewriteVersion': '1.0.0.0',
            'versionnumber': '0.9.9.9',
            'wlsversion': '1',
        }
        self.headers['host'] = 'app.58.com'
        response = requests.get(url=url, params=params, headers=self.headers)
        if response.status_code == 200:
            areas = response.json().get('area').get('result').get('area')
            file = open(self.path, 'w+', encoding='utf-8')
            for area in areas:
                data = f'{area.get("name")} {area.get("pid")} {area.get("id")} {area.get("dirname")}\n'
                file.write(data)
            print('write down')
            file.close()
        else:
            raise Exception(f'location Request fails {response.status_code}')


    @staticmethod
    def key(device_id):
        strs1 = 'wb@D11ncE2Ym4xOJnSWknzi' + f'/common/create_guest_user/?client_version=8.16.5&os_type=android&os_version=6.0.1&client_type=app&appid=10021-wb@aGkl9JkAg9ws&device_id={device_id}&source=2'
        strs2 = hashlib.sha1(strs1.encode('utf-8')).hexdigest() + 'wb@D11ncE2Ym4xOJnSWknzi'
        return hashlib.sha1(strs2.encode('utf-8')).hexdigest()


    def guest_login(self):
        url = f'https://im.58.com/common/create_guest_user/?'
        params = {
            'client_version': '8.16.5',
            'os_type': 'android',
            'os_version': '6.0.1',
            'client_type': 'app',
            'appid': '10021-wb@aGkl9JkAg9ws',
            'device_id': self.imei,
            'source': '2',
            'key': self.key(self.imei)
        }
        self.headers['host'] = 'im.58.com'
        resp = requests.get(url=url, params=params, headers=self.headers, verify=False)
        if resp.status_code == 200:
            user_id = resp.json().get('data').get('user_id')
            user_name = resp.json().get('data').get('user_name')
            print(f'[*]login success -> user_id:{user_id}, user_name:{user_name}')
            self.bangbangid = user_id
            self.headers['bangbangid'] = user_id
        else:
            raise Exception(f'login Request fails {resp.status_code}')

    @staticmethod
    def get_signature(area, times, imei):
        strs = area + '8.16.5' + 'android' + str(imei) + str(times)
        signature = hashlib.md5(strs.encode('utf-8')).hexdigest()
        return signature

    def shop_list(self, area):
        url = f'https://appfang.58.com/api/list/shangpucz?'
        times = int(time.time() * 1000)
        params = {
            'tabkey': 'allcity',
            'action': 'getListInfo',
            'signature': self.get_signature(area, times, self.imei),
            'curVer': '8.16.5',
            'appId': '1',
            'localname': area,
            'os': 'android',
            'format': 'json',
            'geotype': 'baidu',
            'v': '1',
            'ts': times,
            # 'location': '172,177,8777',
            'imei': self.imei,
            'filterParams': '{"userpath":"index_icon_list","param1109":"2","filtercate":"shangpucz","cmcspid":"6656"}',
            'page': '1',
            # 'geoia': '32.036061,118.793313',
            'params': '{}',
        }
        self.headers['Host'] = 'appfang.58.com'
        resp = requests.get(url=url, headers=self.headers, params=params, verify=False)
        if resp.status_code == 200:
            shops = resp.json().get('result').get('getListInfo').get('infolist')
            shop_ids = [shop.get('infoID') for shop in shops]
            return shop_ids
        else:
            raise Exception(f'shop_list Request fails {resp.status_code}')

    @staticmethod
    def get_signature2(id):
        return hashlib.md5(f'{id}HOUSEPHP58'.encode('utf-8')).hexdigest()

    @staticmethod
    def find_index(info, key):
        key_list = [list(info.keys())[0] for info in info]
        return key_list.index(key)


    def shop_info(self, id, area):
        url = f'https://appfang.58.com/api/detail/shangpu/{id}?'
        params = {
            'v': 1,
            'platform': 'android',
            'signature': self.get_signature2(id),
            'version': '8.16.5',
            'commondata': '',
            'sidDict': '',
            'format': 'json',
            'localname': area,
        }
        resp = requests.get(url=url, headers=self.headers, params=params, verify=False)
        if resp.status_code == 200:
            info_list = resp.json().get('result').get('info')
            try:
                shop_info = info_list[self.find_index(info_list, 'business_location_area')].get('business_location_area')
                if shop_info.get('tel'):
                    shop_info = shop_info.get('tel').get('action').get('nativeParam').get('common_tel')
                    info_items = {
                        'title': shop_info.get('action').get('title'),
                        'owner': shop_info.get('action').get('username'),
                        'tel': decrypt_phone(self.scripts, shop_info.get('text')),
                    }
                else:
                    shop_info = info_list[self.find_index(info_list, 'business_brokerinfo_area')].get('business_brokerinfo_area')
                    info_items = {
                        'title': shop_info.get('imAction').get('title'),
                        'owner': shop_info.get('imAction').get('nickname'),
                        'tel': decrypt_phone(self.scripts, shop_info.get('telAction').get('nativeParam').get('common_tel').get('text')),
                    }
                price_info = info_list[self.find_index(info_list, 'business_recommend_area')].get('business_recommend_area').get('items')[0]
                info_items['price'] = price_info.get('price')+price_info.get('priceUnit')
                info_items['area'] = price_info.get('price')+price_info.get('priceUnit')
                info_items['address'] = price_info.get('subTitle')
                info_items['districtLocal'] = price_info.get('districtLocal'),
                info_items['images'] = price_info.get('picUrls')
                # 这里目前只打印
                print(info_items)
            except:
                # 跳过广告推荐
                pass
        else:
            raise Exception(f'shop_list Request fails {resp.status_code}')


    def run(self, area):
        self.guest_login()
        ids = self.shop_list(area)
        print(ids)
        for id in ids:
            self.shop_info(id, area)


if __name__ == '__main__':
    # _58().location_info('hf')
    # _58().shop_list('bj')
    # _58().shop_info('40742527911570', 'bj')
    _58().run(area='hf')
